/* Code licensed under the BSD License: http://www.opensource.org/licenses/bsd-license.php */
/**
* @description <p>Present user name and authorize client for editing.</p>
* @requires PhoneBook, ANVIL, YAHOO, ...
**/

if (typeof PROFILE == "undefined") {
    var PROFILE = {};
}

PROFILE.profileReadyEvent = new YAHOO.util.CustomEvent("profileReadyEvent",PROFILE);

// ISSUE: Should these be PROFILE.changed, meaning the buttons should rewrite and such.

PROFILE.ready_field = false; 
PROFILE.ready = function (bReady) {
    if (arguments.length>0) {
        PROFILE.ready_field = bReady;
        PROFILE.profileReadyEvent.fire(PROFILE);
    }
    return PROFILE.ready_field;
};
PROFILE.setReady = PROFILE.ready;
PROFILE.isReady = PROFILE.ready;

PROFILE.profile = {
    user_name: "Guest", 
    editor: 0,
    role_hint: ""
};

PROFILE.isEditor = function() {
    return PROFILE.profile.editor;
};

PROFILE.write = function () {
    var template = "<p>Welcome {user_name} {role_hint} </p>";
    document.getElementById("profileDiv").innerHTML = template.supplant(PROFILE.profile);
};

PROFILE.result = function(data) {
    if (typeof data.result.user_name != "undefined") { 
        PROFILE.profile.user_name = data.result.user_name;
        PROFILE.profile.editor = parseInt(data.result.editor,10); 
        PROFILE.profile.role_hint = (PROFILE.isEditor()) ? " (editor)" : "";
    }
   PROFILE.setReady(true);
   PROFILE.write();
};   

PROFILE.init = function () {                    
    PhoneBook.rpc.profile(PROFILE.result).call(ANVIL.channel);
};

PROFILE.onRefresh = PROFILE.init;

// -- event bindings --

PROFILE.profileReadyEvent.subscribe(MENU.onProfileReady, MENU); 
MENU.refreshEvent.subscribe(PROFILE.onRefresh, MENU); 
YAHOO.util.Event.onAvailable("profileDiv", PROFILE.init); 
